import {CACHE_EXPIRES_TIME, CACHE_TOKEN, CACHE_USERINFO} from './../config.js';

const formatTime = (type, y, m) => {
  if (typeof type == 'undefined') {
    type = 0;
  }
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  if (type == 1) {
    return [year, month, day].map(formatNumber).join('-');
  } else if (type == 2) {
    return [year, month].map(formatNumber).join('-');
  }

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};

const timeToDate = (value, type = 0) => {
  if (!value) return ""
  value = value * 1000;

  const date = new Date(parseInt(value));
  const year = date.getFullYear();
  const mon = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  if (type == 1) {
    return (mon < 10 ? '0' : '') + mon + '-' + (day < 10 ? '0' : '') + day;
  } else if (type == 2) {
    return year + '/' + mon + '/' + day + " " + hour + ":" + (minute < 10 ? ('0' + minute) : minute);
  } else {
    return year + '/' + mon + '/' + day;
  }

};

/**
 * 获取当前时间信息
 * 1-获取当前年份信息；
 * 2-获取当前月份信息，0-11；
 * 3-获取当前日信息 1-31；
 * 4-获取当前小时信息，0-23；
 * 5-//获取当前分钟信息 0-59；
 * 6-//获取当前秒钟信息，0-59 ；
 * 7-//获取当前毫秒信息 0-999；
 * 8-该时间对象的周信息，0-6；
 * 9-该时间对象的时间戳；
 */
const formatNowDate = function (type = 0) {
  var date = new Date();
  if (type == 1) {
    return date.getFullYear();//获取当前年份信息
  } else if (type == 2) {
    return date.getMonth();//获取当前月份信息，0-11
  } else if (type == 3) {
    return date.getDate();//获取当前日信息 1-31
  } else if (type == 4) {
    return date.getHours();//获取当前小时信息，0-23
  } else if (type == 5) {
    return date.getMinutes();//获取当前分钟信息 0-59
  } else if (type == 6) {
    return date.getSeconds();//获取当前秒钟信息，0-59
  } else if (type == 7) {
    return date.getMilliseconds();//获取当前毫秒信息 0-999
  } else if (type == 8) {
    return date.getDay();//该时间对象的周信息，0-6
  } else if (type == 9) {
    return date.getTime();//该时间对象的时间戳
  } else {
    return date;
  }
}

const formatDate = (value, type = 0) => {
  if (!value) return ""
  var year = value.substring(2, 4);

  if (type == 1) { //年月
    return value.substring(2, 7);
  } else if (type == 2) { //月日 小时:分钟
    return value.substring(5, 16);
  } else if (type == 3) {
    return value.substring(5, 10);
  } else if (type == 4) {//年月日 小时:分钟
    return value.substring(2, 16);
  } else if (type == 5) {//年月日
    return value.substring(2, 10);
  } else if (type == 6) {//年月日 (yyyy-mm-dd)
    return value.substring(0, 10);
  } else if (type == 7) {//年 (yyyy)
    return value.substring(0, 4);
  }

  return year;
};

// 判断空
const isEmpty = (value) => {
  if (value == null || value == "" || value == "undefined" || value == undefined || value == "null") {
    return true;
  } else {
    if (typeof value == "string") {
      value = value.replace(/\s/g, "");
    } else if (typeof value == "object" && Object.keys(value).length == 0) {
      return true;
    }
    if (value == "") {
      return true;
    }
    return false;
  }
}

const activityDate = (value) => {
  if (!value) return value;
  var year = value.substring(0, 4);
  var month = value.substring(5, 7);
  var day = value.substring(8, 10);
  var hour = value.substring(11, 13);
  var min = value.substring(14, 16);
  return month + '月' + day + '日' + hour + ':' + min;
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

/**
 * 处理服务器扫码带进来的参数
 * @param string param 扫码携带参数
 * @param string k 整体分割符 默认为：&
 * @param string p 单个分隔符 默认为：=
 * @return object
 *
 */
const getUrlParams = (param, k, p) => {
  if (typeof param != 'string') {
    return {};
  }
  k = k ? k : '&';// 整体参数分隔符
  p = p ? p : '=';// 单个参数分隔符
  const value = {};
  if (param.indexOf(k) !== -1) {
    param = param.split(k);
    for (const val in param) {
      if (param[val].indexOf(p) !== -1) {
        const item = param[val].split(p);
        value[item[0]] = item[1];
      }
    }
  } else if (param.indexOf(p) !== -1) {
    const item = param.split(p);
    value[item[0]] = item[1];
  } else {
    return param;
  }
  return value;
};

const wxgetUserInfo = function (data) {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      desc: '业务需要',
      lang: 'zh_CN',
      success(res) {
        resolve(res);
      },
      fail(res) {
        reject(res);
      }
    });
  });
};

const showModelTip = function (content, title = "", confirmText = '', cancelText = "", showCancel = true) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: title || '温馨提示',
      content: content,
      showCancel: showCancel,
      cancelText: cancelText || '取消',
      cancelColor: '#000000',
      confirmText: confirmText || '确定',
      confirmColor: '#42C6A5',
      success: (res) => {
        resolve(res);
      }
    })
  });
}

const checkLogin = function (token, expiresTime, isLog) {

  if (getApp()) {
    token = getApp().globalData.token;
    isLog = isLog == true ? isLog : getApp().globalData.isLog;
  }

  token = true;
  const res = !!token;
  const res1 = isLog;
  const res2 = res && res1;

  return res2;
};

const logout = function () {

  if (!isEmpty(getApp())) {
    getApp().globalData.token = '';
    getApp().globalData.isLog = false;
    getApp().globalData.userInfo = [];
  }

  const shared_id = wx.getStorageSync('shared_id');//分享会员

  wx.clearStorageSync();
  wx.clearStorage();
  wx.removeStorageSync('cache_key');

  if (shared_id) {
    wx.setStorageSync('shared_id', shared_id)
  }

};

const chekWxLogin = function (type, scene) {

  if (type == 1) {
    logout();
  } else {
    //检测token 是否有效
    const token_expire_time = wx.getStorageSync(CACHE_EXPIRES_TIME);
    const current_timestamp = Date.parse(new Date()); //当前时间戳
    //缓存时间小于当前时间
    if (token_expire_time <= current_timestamp) {
      logout();
    }
  }

  return new Promise((resolve, reject) => {
    if (checkLogin()) {
      return resolve({
        userInfo: getApp().globalData.userInfo,
        isLogin: typeof getApp().globalData.userInfo.id != 'undefined'
      });
    }

    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          return reject({authSetting: false});
        } else {
          wx.getStorage({
            key: 'cache_key',
            success(res) {
              return resolve({userInfo: res.data, isLogin: false});
            },
            fail() {
              getCodeLogin((code) => {
                const sendData = {code: code.code};
                if (scene) {
                  sendData.scene = scene;
                }
                sendData['client_version'] = __wxConfig.envVersion;
                sendData['share_id'] = wx.getStorageSync("shared_id")

                wx.request({  // 登录信息
                  url: getApp().globalData.url + '/api/login',
                  method: 'POST',
                  data: sendData,
                  success: function (result) {
                    if (result.statusCode !== 200) {
                      reject(result.data.msg || "");
                      return
                    }

                    //未授权手机号码之前
                    /*if (isEmpty(result.data.data) || isEmpty(result.data.data.id)) {
                      wx.setStorageSync('openid', result.data.data.openid || "");
                      wx.redirectTo({
                        url: '/pages/public/verify_mobile'
                      })
                      return;
                    }*/
                    // console.log()
                    setUserCache(result);  // 保存cache
                    if (getCurrentPages().length > 0) {
                      wx.setStorageSync('is_login_refresh', 1)
                    }

                    return resolve({
                      userInfo: result.data.data,
                      isLogin: typeof result.data.data.id != 'undefined'
                    });
                  },
                  fail: function (res) {
                    reject(res);
                  }
                });
              });
            }
          });
        }
      },
      fail(res) {
        return reject(res);
      }
    });
  });
};

const setUserCache = function (result, type = 0) {
  const app = getApp(),
    that = this,
    current_userInfo = result.data.data;
  let jessionid = result.header['Set-Cookie'];

  if (result.header['debug-cookie']) {
    wx.setStorageSync('JSESSIONID', 'SESSIONID=' + result.header['debug-cookie']);
  } else if (jessionid) {
    const start = jessionid.indexOf('SESSIONID');
    const end = jessionid.indexOf(';', start);
    jessionid = jessionid.substring(start, end);
    // 2 保存JESSIONID
    wx.setStorageSync('JSESSIONID', jessionid);
  }

  console.log("current_userInfo", current_userInfo)

  app.globalData.token = true;
  app.globalData.isLog = true;
  app.globalData.userInfo = current_userInfo || "";

  wx.setStorageSync(CACHE_TOKEN, true);
  wx.setStorageSync("cookie_token", current_userInfo.token || '');

  const expire_time = Date.parse(new Date()) + +23 * 3600 * 1000;
  wx.setStorageSync(CACHE_EXPIRES_TIME, expire_time);   //有效期 Token

  wx.setStorageSync(CACHE_USERINFO, JSON.stringify(current_userInfo));
  if (current_userInfo.cancel == 0) {//账户取消后直接跳转到恢复
    wx.redirectTo({
      url: '/pages/member/recover'
    })
  }
};

/**
 *
 * 授权过后自动登录
 */
const autoLogin = function () {
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: 'cache_key',
      success(res) {
        return resolve({userInfo: res.data, isLogin: false});
      },
      fail() {
        getCodeLogin((code) => {
          wx.request({  // 登录信息
            url: getApp().globalData.url + '/api/login',
            method: 'POST',
            header: {
              'cookie': wx.getStorageSync('JSESSIONID')
            },
            data: {code: code.code},
            success: function (result) {
              setUserCache(result);  // 保存cache
              return resolve({userInfo: result.data.data, isLogin: !!result.data.data.id});
            },
            fail: function (res) {
              return reject(res);
            }
          });
        });
      }
    });
  });
};

const getCodeLogin = function (successFn) {
  wx.login({
    success(res) {
      successFn(res);
    }
  });
};

/*
* 合并数组
*/
const SplitArray = function (list, sp) {
  if (typeof list != 'object') {
    return [];
  }
  if (sp === undefined) {
    sp = [];
  }

  for (let i = 0; i < list.length; i++) {
    sp.push(list[i]);
  }

  return sp;
};

/*
* 合并对象
*/
const SplitObject = function (list, sp) {
  if (typeof list !== 'object') {
    return {};
  }
  if (!list) {
    return sp;
  }
  if (sp === undefined) {
    sp = {};
  }

  for (const k in list) {
    if (typeof sp[k] === 'undefined') {
      sp[k] = list[k];
    }
  }

  return sp;
};

/**
 * opt  object | string
 * to_url object | string
 * 例:
 * this.Tips('/pages/test/test'); 跳转不提示
 * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
 * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
 * tab=1 一定时间后跳转至 table上
 * tab=2 一定时间后跳转至非 table上
 * tab=3 一定时间后返回上页面
 * tab=4 关闭所有页面跳转至非table上
 * tab=5 关闭当前页面跳转至非table页面
 */
const Tips = function (opt, to_url) {

  if (typeof opt == 'string') {
    to_url = opt;
    opt = {};
  }

  const title = opt.title || '', icon = opt.icon || 'none', endtime = opt.endtime || 2000;
  if (title) {
    wx.showToast({title: title, icon: icon, mask: !opt.hideMask, duration: endtime});
  }

  if (to_url != undefined) {
    if (typeof to_url == 'object') {
      const tab = to_url.tab || 1, url = to_url.url || '';
      switch (tab) {
        case 1:
          // 一定时间后跳转至 table
          setTimeout(function () {
            wx.switchTab({
              url: url
            });
          }, endtime);
          break;
        case 2:
          // 跳转至非table页面
          setTimeout(function () {
            wx.navigateTo({
              url: url
            });
          }, endtime);
          break;
        case 3:
          // 返回上页面
          setTimeout(function () {
            wx.navigateBack({
              delta: parseInt(url)
            });
          }, endtime);
          break;
        case 4:
          // 关闭当前所有页面跳转至非table页面
          setTimeout(function () {
            wx.reLaunch({
              url: url
            });
          }, endtime);
          break;
        case 5:
          // 关闭当前页面跳转至非table页面
          setTimeout(function () {
            wx.redirectTo({
              url: url
            });
          }, endtime);
          break;
      }

    } else if (typeof to_url == 'function') {
      setTimeout(function () {
        to_url && to_url();
      }, endtime);
    } else {
      // 没有提示时跳转不延迟
      setTimeout(function () {
        wx.navigateTo({
          url: to_url
        });
      }, title ? endtime : 0);
    }
  }
};

/**
 * 移除数组中的某个数组并组成新的数组返回
 * @param array array 需要移除的数组
 * @param int index 需要移除的数组的键值
 * @param string | int 值
 * @return array
 *
 */
const ArrayRemove = (array, index, value) => {
  const valueArray = [];
  if (array instanceof Array) {
    for (let i = 0; i < array.length; i++) {
      if (typeof index == 'number' && array[index] != i) {
        valueArray.push(array[i]);
      } else if (typeof index == 'string' && array[i][index] != value) {
        valueArray.push(array[i]);
      }
    }
  }
  return valueArray;
};


const checkPhone = (mobile) => {
  if (!(/1[3-9]\d{9}$/.test(mobile))) {
    // if(!preg_match('/^1[3-9][0-9]\d{8}$/', $mobile)){
    return false;
  }
  return true;
};


const subTen = (value) => value < 10 ? ('0' + value) : value;

/**
 * 获取设备信息
 * @returns {Promise<any>}
 */
const wechatGetSystemInfo = function () {
  return new Promise((resolve, reject) => {
    wx.getSystemInfo({
      success: (res) => {
        resolve(res)
      }, fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 *  获取设备信息
 *  底部黑线适配
 */
const checkIphone = function () {
  return new Promise((resolve, reject) => {
    let isIphoneX = false

    wechatGetSystemInfo().then(res => {
      let modelmes = res.model;
      //console.log(modelmes);
      let iphoneArr = ['iPhone X', 'iPhone 11', 'iPhone 12', 'iPhone 13', 'iPhone 14']

      for (const key in iphoneArr) {
        if (modelmes.search(iphoneArr[key]) != -1) {
          isIphoneX = true;
          break;
        }
      }
      resolve(isIphoneX)
    })
  })
  return isIphoneX
}

const isIphone = function () {
  return new Promise((resolve, reject) => {
    let isIphone = false
    wechatGetSystemInfo().then(res => {
      let modelmes = res.model;
      //console.log(modelmes);
      if (modelmes.search('iPhone') != -1) {
        isIphone = true;
      }

      resolve(isIphone)
    })
  })
  return isIphone
}


/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
function formatRichText(html) {
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
    match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
    match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
  return newContent;
}


/**
 * params1： url
 * params2： 要获取参数
 */
const getQueryString = (url, name) => {
  var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  var r = url.substr(1).match(reg)
  if (r != null) {
    // console.log("r = " + r)
    // console.log("r[2] = " + r[2])
    return r[2]
  }
  return null;
}

/**
 * 获取当前页面带参数的路径
 * pages/elect-pool/my?share_id=5
 */
const getCurrentPath = () => {
  let userInfo = wx.getStorageSync(CACHE_USERINFO)
  userInfo = userInfo ? JSON.parse(userInfo) : [];//获取当前用户信息

  if (userInfo.length > 0)
    return false;

  var share_id = userInfo.id;//当前用户id
  if (isEmpty(share_id)) {
    return false;
  }
  wx.setStorageSync('share_id', share_id);
  var pages = getCurrentPages();//获取加载的页面
  var view = pages[pages.length - 1]; //获取当前页面的对象
  var options = Object.entries(view.options);//该页面参数
  var params = "?";//处理该页面的参数
  if (options.length > 0) {
    var newarr = SplitArray(options, [["share_id", share_id]]);//合并分享人参数
    newarr.forEach((elem, index) => {
      if (newarr.length - 1 == index) {
        params = params + elem[0] + "=" + elem[1];
      } else {
        params = params + elem[0] + "=" + elem[1] + "&";
      }
    });
  } else {
    params = params + "share_id=" + share_id;
  }
  if (userInfo.award_type == 1) {
    params = params + "&at=" + userInfo.award_type;
  }

  return view.route + params;//完整页面路径
};

const saveImg = function (url) {
  if (!url) return this.Tips({title: "图片地址必填"})
  var that = this;
  wx.downloadFile({
    url: url,
    success(res) {
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          return that.Tips({title: "保存成功", icon: "success"})
        },
        fail: res => {
          return that.Tips({title: "保存失败", icon: "error"})
        }
      })
    }
  })
}

/**
 * type   ： 1：不需要切图
 * @param image
 * @param width
 * @param height
 * @param type
 * @returns {string|boolean|*}
 */
const previewCdnImage = function (image, width = 0, height = 0, type = 0) {
  let img_domain = "https://mini.sideupnow.net";
  if (!image || image.indexOf("http") >= 0) {
    return image;
  }
  if (!width && !height) {
    return img_domain + image;
  }
  return img_domain + image;
}


module.exports = {
  formatTime: formatTime,
  formatNumber: formatNumber,
  checkPhone: checkPhone,
  Tips: Tips,
  showModelTip: showModelTip,
  SplitArray: SplitArray,
  SplitObject: SplitObject,
  ArrayRemove: ArrayRemove,
  getUrlParams: getUrlParams,
  getCodeLogin: getCodeLogin,
  chekWxLogin: chekWxLogin,
  checkLogin: checkLogin,
  wxgetUserInfo: wxgetUserInfo,
  autoLogin: autoLogin,
  logout: logout,
  subTen: subTen,
  wechatGetSystemInfo: wechatGetSystemInfo,
  checkIphone: checkIphone,
  isIphone: isIphone,
  activityDate: activityDate,
  formatRichText: formatRichText,
  isEmpty: isEmpty,
  timeToDate: timeToDate,
  formatDate: formatDate,
  formatNowDate: formatNowDate,
  getQueryString: getQueryString,
  getCurrentPath: getCurrentPath,
  previewCdnImage: previewCdnImage,
  saveImg: saveImg,
};
